const query = require("../db/mysql");
const {success, error} = require('../model/model')
class CartController {
    // 获取购物车列表
    getCartList = async  (ctx) =>{
        const {user_id} = ctx.query;
        const sql = `select * from carts where user_id="${user_id}"`
        const data =await query(sql)
        // data 数组
        // 循环里怎么放异步
        // 返回一个由Promise组成的数组
        const allP = data.map(item => {
            return query(`select * from shops where id="${item.shop_id}"`)
        })
        const shops= await Promise.all(allP); // 接收一个由Promise组成的数组  当所有的promise都resolve时返回resolve
        // 只要有一个promise变为reject 则返回reject   ---- 一假则假
        const newData = data.map((item,index) => {
            return { ...shops[index][0],...item}
        })
        ctx.body = success(newData)
    }
    addToCart = async  (ctx) =>{
        // post
        const {user_id, shop_id} = ctx.request.body;
        // 判断此商品是不是第一次添加
        const isHaveSql = `select * from carts where user_id="${user_id}" and shop_id="${shop_id}"`
        // [] [{}]
        const isHave = await query(isHaveSql)
        let sql = ''
        if(isHave.length) {
            console.log(isHave)
            const nowData = isHave[0]; // { id: 2, shop_id: 99, user_id: 1, count: 4 }
            // 如果不是第一次 则执行count++操作
            sql = `update carts set count="${nowData.count+=1}"  where id="${nowData.id}"`
        } else {
            // 如果是第一次 则指向添加操作 count默认为1
            sql = `insert into carts(user_id,shop_id,count) values("${user_id}","${shop_id}",1)`
        }
        const data =await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('添加成功')
        } else {
            ctx.body = error('添加失败')
        }
    }
    delCart = async(ctx) => {
        const {id} = ctx.params;
        const sql = `delete from carts where id ="${id}"`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('删除成功')
        } else {
            ctx.body = error('删除失败')
        }
    }
    setCartCount= async(ctx) => {
        const {id,count} = ctx.request.body;
        const sql = `update carts set count="${count}" where id="${id}"`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('更新成功')
        } else {
            ctx.body = error('更新失败')
        }
    }
}   

module.exports = new CartController()